from itertools import islice

import requests
from pyecharts import options as opts
from pyecharts.charts import Radar
from pyecharts.globals import ThemeType
import re
def get_one_page(url):
    """
    发起Http请求，获取Response的响应结果
    """
    ua_headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"}
    reponse = requests.get(url, headers=ua_headers)
    if reponse.status_code == 200:  # ok
        return reponse.text
    return None


def extract_first_number(text):
    pattern = r"\d+"  # 匹配数字的正则表达式
    match = re.search(pattern, text)
    if match:
        return int(match.group())  # 返回匹配到的数字
    else:
        return None  # 如果没有匹配到数字，返回 None


def parse_one_page(html):
    pattern = r"<tr>\s*<td>.*?</td>\s*<td>(.*?)</td>\s*<td>.*?</td>\s*<td>(.*?)</td>\s*<td>(.*?)</td>"
    matches = re.findall(pattern, html, re.DOTALL)
    data_list = []
    for match in islice(matches, 2):
        api = extract_first_number(match[0])
        pm25 = extract_first_number(match[1])
        pm10 = extract_first_number(match[2])
        data_list.append([api, pm25, pm10])
    return data_list



def CrawlWebPages():
    """
    8.空气质量雷达图
    """
    url = 'https://www.air-level.com/air/xining'
    # 抓取当前的页面
    html = get_one_page(url)
    if html is None:
        print("此网页爬取失败：" + url)
    # print(html)
    # 这里的for
    data_list=parse_one_page(html)
    return data_list
data_list=CrawlWebPages()
new_data_list1=[data_list[0]]
new_data_list2=[data_list[1]]
print('开始绘制空气质量雷达图...')
c_schema = [
    {"name": "AQI", "max": 200, "min": 20},
    {"name": "PM2.5 μg/m", "max": 200, "min": 20},
    {"name": "PM10 μg/m", "max": 200, "min": 20},
]
Radar1 = (

    Radar(opts.InitOpts(theme=ThemeType.DARK, height="400px", width="300px", chart_id='Radar1',
                        bg_color="rgba(16, 12, 42,0.8)"))
    .add_schema(schema=c_schema, shape="circle")
    .add("青海师大监测站           ", new_data_list1, color="#4f9fff")
    .add("西宁世纪职校监测站", new_data_list2, color="#7cffb2")
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(title_opts=opts.TitleOpts(title='空气质量雷达图',
                                               title_textstyle_opts=opts.TextStyleOpts(
                                                   font_size=15,
                                                   # 标题的字体大小
                                                   font_family='微软雅黑',
                                               ),
                                               pos_left='left',
                                               pos_top='23px')))

Radar1.render("8.空气雷达图.html")
